package com.chixing.service.impl;

import com.chixing.entity.Car;
import com.chixing.entity.Orders;
import com.chixing.mapper.CarMapper;
import com.chixing.mapper.OrdersMapper;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Component
public class PayServiceImpl {
    @Autowired
    private OrdersMapper ordersMapper;

    //普通队列消费者 -- 普通支付
    @RabbitHandler
    @RabbitListener(queues = "payQueue")
    public void pay(Map map, Channel channel, Message message){

        Orders orders = (Orders) map.get("orders");
        Orders order = ordersMapper.selectById(orders.getOrderId());

        if (order.getOrderStatus() == 1){
            System.out.println("---订单已支付---");
            System.out.println("---库存-1---");
        }else {
            System.out.println("订单状态异常！");
        }

        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //死信队列消费者 -- 延时支付
    @RabbitHandler
    @RabbitListener(queues = "deadQueue")
    public void cancelPay(Map map, Channel channel, Message message){
        Orders orders = (Orders) map.get("orders");
//        Integer carId = (Integer) map.get("carId");
        Orders order = ordersMapper.selectById(orders.getOrderId());

        if (order.getOrderStatus() == 0){
            order.setOrderStatus(2);
            ordersMapper.updateById(order);
            System.out.println("超过限定时间，用户订单已经取消");
        }

        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
